package com.yiren.dbaa.module.device.view.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yiren.backstage.currency.utils.FileUtil;
import com.yiren.dbaa.R;
import com.yiren.dbaa.constant.AddressConstant;

import java.io.File;
import java.text.DecimalFormat;

/**
 * Created by WANGRONGXIANG
 * on 2022/6/14
 * Describe 更新带进度条的会话框
 */
public class DownloadStatusDialog {

    private Activity activity;
    private int total;     //总进度
    private int sumProgressBarPosition = 0; //进度条累计进度

    private AlertDialog dialog;
    private TextView tvDownloadRate;
    private ProgressBar pbDownloadProgress;

    private DecimalFormat df = new DecimalFormat("######0.00"); //百分比格式化工具

    public DownloadStatusDialog(Activity activity, int total) {
        this.activity = activity;
        this.total = total;
    }

    public void show() {
        dialog = new AlertDialog.Builder(activity).create();
        dialog.setCancelable(false);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_download_status);
        TextView tvDownloadName = (TextView) window.findViewById(R.id.tv_download_name);
        TextView tvDownloadSize = (TextView) window.findViewById(R.id.tv_download_size);
        tvDownloadRate = (TextView) window.findViewById(R.id.tv_download_rate);
        pbDownloadProgress = (ProgressBar) window.findViewById(R.id.pb_download_progress);
        TextView btnCancel = (TextView) window.findViewById(R.id.btn_cancel);
        TextView btnHide = (TextView) window.findViewById(R.id.btn_hide);
        // 给弹出框的控件赋值，因为要用到oos的下载信息，所以和实例化控件分开写
        tvDownloadName.setText("名称：" + AddressConstant.HOST_MACHINE_NAME);
        Double downloadSize = (double) total / (1024 * 1024);
        tvDownloadSize.setText("大小：" + df.format(downloadSize) + "MB");
        tvDownloadRate.setText("0%");
        // 设置进度条的最大值
        pbDownloadProgress.setMax(total);
        btnCancel.setOnClickListener(v -> {
            File file = new File(FileUtil.fetchAvailableSdcardFoloder() + "/yiren/dbaf/update.rar");
            if (file.exists()) file.delete();
            dialog.dismiss();
        });
        btnHide.setOnClickListener(v -> dialog.dismiss());
    }

    /**
     * 关闭对话框
     */
    public void close() {
        if (null != dialog) dialog.dismiss();
    }

    public void refreshProgress(int len) {
        // 当前进度
        sumProgressBarPosition += len;
        // 设置当前进度条的当前进度
        pbDownloadProgress.setProgress(sumProgressBarPosition);
        tvDownloadRate.setText(df.format(((double) sumProgressBarPosition / total) * 100) + "%");
    }
}


